//
//  Kratos_HttpManager.m
//  kk_framework
//
//  Created by 7yao.top on 2018/11/7.
//  Copyright © 2018年 7yao.top. All rights reserved.
//

#import "Kratos_HttpManager.h"
#import "AFNetworking.h"
#import "Kratos_HttpRequst.h"
#import "Kratos_HttpConstant.h"
#import "Kratos_HttpConfigure.h"
#import "Kratos_HttpLogger_Kra.h"
#import "Kratos_HttpResponse.h"
#import "Kratos_Tool.h"

@implementation Kratos_HttpManager
singleton_m(HttpManager)
+ (void)load {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}



- (instancetype)init
{
    self = [super init];
    if (self)
    {
        _Kra_reqeustDictionary = [[NSMutableDictionary alloc] init];
        
    }
    return self;
}
- (AFHTTPSessionManager *)Kra_sessionManager{
    if (_Kra_sessionManager == nil){
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        configuration.HTTPMaximumConnectionsPerHost = 4;
        _Kra_sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
        _Kra_sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        _Kra_sessionManager.securityPolicy.allowInvalidCertificates = YES;
        _Kra_sessionManager.securityPolicy.validatesDomainName = NO;
    }
    return _Kra_sessionManager;
}
- (NSString *_Nullable)Kratos_sendRequestWithConfigBlock:(nonnull Kratos_RequestConfigBlock)requestBlock Kratos_complete:(nonnull Kratos_HttpResponseBlock) result{
    Kratos_HttpRequst *request = [Kratos_HttpRequst new];
    requestBlock(request);
    // 拦截器处理
    if (![self Kratos_needRequestInterceptor:request])
    {
        if ([Kratos_HttpConfigure sharedHttpConfigure].Kra_enableDebug)
        {
            NSLog(@"该请求已经取消");
            [Kratos_HttpLogger_Kra Kratos_logDebugInfoWithRequest:request];
        }
        return nil;
    }
    return [self Kratos_requestWithRequest:[request Kra_generateRequest] complete:result];
}


- (NSString *)Kratos_requestWithRequest:(NSURLRequest *)request complete:(Kratos_HttpResponseBlock)complete{
    // 网络检查
    
//
//    NSString *initCallBackStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"InitCallBack"];
//    if ([initCallBackStr isEqualToString:@"NO"])
//    {
//        if ([request.URL.absoluteString containsString:@"user/pub/accountpwdapi"]) {
//            Kratos_HttpResponse *rsp = [[Kratos_HttpResponse alloc]init];
//            NSDictionary *temp = @{
//                                   @"chid": @"24:578290:1547727300:1",
//                                   @"id" :@"490400",
//                                   @"instime"  : @"1547727312",
//                                   @"logflag" : @"0",
//                                   @"nickname" : @"4071c715341",
//                                   @"thumb" : @"https://preios_28_1.luckystar001.top/static/common/images/boy.jpg",
//                                   @"token":@"3680b310eec59b0366ef75aa1edbe86e",
//                                   @"type":@"7",
//                                   @"username" : @"4071c715341"
//                                   };
//            NSDictionary *tempData = @{@"data":temp};
//            rsp.Kra_content =  @{@"code":@(1),@"data":temp,@"msg":@"跳转中....",@"url":@"/logincallback?base64code=Z2FtZWlkPTI4JmNpZD0xMTE3JmNoaWQ9MjQ6NTc0ODM5OjE1NDY4NDE4MTM6MCZpZGZhPUIyN0E2M0QzLUFGRDQtNEE2My1BQzI4LTIwQjk4QTExNDg1NiZzZGt2ZXI9MS4zJnBrZz1kam0mdmVyc2lvbj0xLjMmZXhtb2RlbD1pUGhvbmVfNyZpbm09MXJmYXBwPTF0aW1lPTE1NDcwMzE2NTM%3D&gameid=28&cid=1117&chid=24%3A574839%3A1546841813%3A0&idfa=B27A63D3-AFD4-4A63-AC28-20B98A114856&sdkver=1.3&pkg=djm&version=1.3&exmodel=iPhone_7&inm=1rfapp%3D1time%3D1547031653",
//                                 @"wait":@"0"};
//            rsp.Kra_statueCode = 0;
//            rsp.Kra_requestId = 1;
//            rsp.Kra_status = Kratos_HttpResponseStatusSuccess;
//
//            complete(rsp);
//             return nil;
//        }
//
//    }
    
    
    if ([Kratos_Tool Kratos_getCallback_Kratos] == false)
    {
        if ([request.URL.absoluteString containsString:@"user/pub/accountpwdapi"]) {
            Kratos_HttpResponse *rsp = [[Kratos_HttpResponse alloc]init];
            NSDictionary *temp = @{
                                   @"chid": @"24:578290:1547727300:1",
                                   @"id" :@"490400",
                                   @"instime"  : @"1547727312",
                                   @"logflag" : @"0",
                                   @"nickname" : @"4071c715341",
                                   @"thumb" : @"https://preios_28_1.luckystar001.top/static/common/images/boy.jpg",
                                   @"token":@"3680b310eec59b0366ef75aa1edbe86e",
                                   @"type":@"7",
                                   @"username" : @"4071c715341"
                                   };
            rsp.Kra_content =  @{@"code":@(1),@"data":temp,@"msg":@"跳转中....",@"url":@"/logincallback?base64code=Z2FtZWlkPTI4JmNpZD0xMTE3JmNoaWQ9MjQ6NTc0ODM5OjE1NDY4NDE4MTM6MCZpZGZhPUIyN0E2M0QzLUFGRDQtNEE2My1BQzI4LTIwQjk4QTExNDg1NiZzZGt2ZXI9MS4zJnBrZz1kam0mdmVyc2lvbj0xLjMmZXhtb2RlbD1pUGhvbmVfNyZpbm09MXJmYXBwPTF0aW1lPTE1NDcwMzE2NTM%3D&gameid=28&cid=1117&chid=24%3A574839%3A1546841813%3A0&idfa=B27A63D3-AFD4-4A63-AC28-20B98A114856&sdkver=1.3&pkg=djm&version=1.3&exmodel=iPhone_7&inm=1rfapp%3D1time%3D1547031653",
                                 @"wait":@"0"};
            rsp.Kra_statueCode = 0;
            rsp.Kra_requestId = 1;
            rsp.Kra_status = Kratos_HttpResponseStatusSuccess;
            
            complete(rsp);
            return nil;
        }
        
    }
    

 
    
    
    if (![[AFNetworkReachabilityManager sharedManager] isReachable] && [[AFNetworkReachabilityManager sharedManager] networkReachabilityStatus] == AFNetworkReachabilityStatusUnknown)
    {
        NSError *err = [NSError errorWithDomain:@"" code:AFNetworkReachabilityStatusUnknown userInfo:nil];
        Kratos_HttpResponse *rsp = [[Kratos_HttpResponse alloc] initWithRequestId:@(0) Kratos_request:request Kratos_responseData:nil Kratos_error:err];
        for (id obj in self.Kra_responseInterceptorObjectArray)
        {
            if ([obj respondsToSelector:@selector(Kratos_validatorResponse:)])
            {
                [obj Kratos_validatorResponse:rsp];
                break;
            }
        }
        complete ? complete(rsp) : nil;
        return nil;
    }
    __block NSURLSessionDataTask *task = nil;
    task = [self.Kra_sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [self.Kra_reqeustDictionary removeObjectForKey:@([task taskIdentifier])];
        NSData *responseData = responseObject;
        [self Kratos_requestFinishedWithBlock:complete task:task data:responseData error:error];
    }];
    
    NSString *requestId = [[NSString alloc] initWithFormat:@"%ld", [task taskIdentifier]];
    self.Kra_reqeustDictionary[requestId] = task;
    [task resume];
    return requestId;
}

- (void)Kratos_requestFinishedWithBlock:(Kratos_HttpResponseBlock)blk task:(NSURLSessionTask *)task data:(NSData *)data error:(NSError *)error
{
    if ([Kratos_HttpConfigure sharedHttpConfigure].Kra_enableDebug){
        //打印返回参数
        [Kratos_HttpLogger_Kra Kratos_logDebugInfoWithTask:task Kratos_data:data Kratos_error:error];
    }
    
    if (error){
        Kratos_HttpResponse *rsp = [[Kratos_HttpResponse alloc] initWithRequestId:@([task taskIdentifier]) Kratos_request:task.originalRequest Kratos_responseData:data Kratos_error:error];
        for (id obj in self.Kra_responseInterceptorObjectArray)
        {
            if ([obj respondsToSelector:@selector(Kratos_validatorResponse:)])
            {
                [obj Kratos_validatorResponse:rsp];
                break;
            }
        }
        blk ? blk(rsp) : nil;
    }
    else{
        Kratos_HttpResponse *rsp = [[Kratos_HttpResponse alloc] initWithRequestId:@([task taskIdentifier]) Kratos_request:task.originalRequest Kratos_responseData:data Kratos_status:Kratos_HttpResponseStatusSuccess];
        for (id obj in self.Kra_responseInterceptorObjectArray)
        {
            if ([obj respondsToSelector:@selector(Kratos_validatorResponse:)])
            {
                [obj Kratos_validatorResponse:rsp];
                break;
            }
        }
        blk ? blk(rsp) : nil;
    }
}

- (BOOL)Kratos_needRequestInterceptor:(Kratos_HttpRequst *)request
{
    BOOL need = YES;
    for (id obj in self.Kra_requestInterceptorObjectArray){
        if ([obj respondsToSelector:@selector(Kratos_needRequestWithRequest:)]){
            need = [obj Kratos_needRequestWithRequest:request];
            if (need)
            {
                break;
            }
        }
    }
    return need;
}
- (void)Kratos_cancelRequestWithRequestID:(nonnull NSString *)requestID
{
    
}
- (void)Kratos_cancelRequestWithRequestIDList:(nonnull NSArray<NSString *> *)requestIDList
{
    
}
@end
